package com.jiepos.mpos.inter.message.service.nanchuang;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.jiepos.mpos.core.util.StringUtils;
import com.jiepos.mpos.inter.message.service.AbrPhoneMessageService;
import com.jiepos.mpos.inter.message.service.IPhoneMessageService;

/**
 * 阅信-短信验证码接口
 * @author Zhao.Jinkui
 * @version 1.0
 * @ProjectName: mpos
 * @Package com.jiepos.mpos.inter.message.service.nanchuang
 * @ClassName YueXinPhoneMessageService
 * @history
 * @UpdateRemark []
 * @since 2017/10/12
 */
@Service
public class YueXinPhoneMessageService extends AbrPhoneMessageService implements IPhoneMessageService {

    //阅信-短信平台请求地址
    private static String URL= "http://106.14.55.160:9000/HttpSmsMt";

    @Override
    public Map sendMessage(String name,String pwd,String phoneNum,String content,String ins_cd) {
        // 下发时间
        String mttime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        Map<String, String> param = new HashMap<>();
        param.put("name", name);
        param.put("pwd", this.MD5(pwd + mttime));
        try {
            //短信内容（必选）
            param.put("content", URLEncoder.encode(content.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //手机号码（必选）国内号码：11 位的有效手机号码。国际号码：00 开头＋国家码＋手机号码
        param.put("phone", phoneNum);
        /*  扩展码（可选）用户自定义的子用户接入号扩展码 当有多个签名时，该字段必选
            一个扩展码必须对应一个签名,一个签名可以对应多个扩展码。
            扩展码建议不超过 7 位。
         */
        if(!StringUtils.isBlank(ins_cd)){
            param.put("subid", "");
        }
        //提交时间（必选）时间格式：yyyyMMddhhmmss
        param.put("mttime", mttime);
        //返回数据类型（必选）值为：0 返回 Xml 格式（过时）值为：1 返回 Json 格式（推荐）
        param.put("rpttype", "1");
        //发送下行消息
        String result = sendPost(param);
        //返回结果 00 -- 成功
        return JSON.parseObject(result);
    }

    private String sendPost(Map<String, String> params) {
        URL u = null;

        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Map.Entry<String, String> e : params.entrySet()) {
                sb.append(e.getKey()).append("=").append(e.getValue()).append("&");
            }
            sb.substring(0, sb.length() - 1);
        }
        // 尝试发送请求
        try {
            u = new URL(URL);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setConnectTimeout(6000);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(sb.toString());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();

            }
        }
        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp).append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    //MD5加密
    private String MD5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        char[] charArray = str.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}
